import os from "os"

import Koa from "koa"
import Router from "@koa/router"
import cors from "koa2-cors"
import { koaBody } from "koa-body"

import fs from "fs-extra"
import path from "path"
import chalk from "chalk"
import AdmZip from "adm-zip"
import { desktopPath } from "@/utils"

const app = new Koa()

const router = new Router()

router.all("/status", (ctx, next) => {
  ctx.body = "野pig!"

  next()
})

// const uploadDir = path.join(__dirname, "upload")
const uploadDir = fs.mkdtempSync(path.join(os.tmpdir(), "uploadDir-"))

app.use(
  koaBody({
    multipart: true,
    formidable: {
      keepExtensions: true,
      uploadDir,
      maxFileSize: 1024 * 1024 * 1024 * 10,
      onFileBegin(name, file) {
        // fs.ensureDirSync(uploadDir)
        // fs.rmSync(uploadDir, { recursive: true, force: true })
        fs.ensureDirSync(uploadDir)
        const { filepath, newFilename, originalFilename } = file
        file.filepath = filepath.replace(newFilename, originalFilename || "")
      },
    },
  }),
)

router.post("/upload", async (ctx, next) => {
  let res = {
    status: 200,
    msg: "上传成功",
  }

  try {
    for (const key in ctx.request.files) {
      const file = ctx.request.files[key]

      if (!Array.isArray(file)) {
        const { name: targetFolder } = path.parse(file.filepath)

        const zip = new AdmZip(file.filepath)

        const tmpDir = path.join(__dirname, "tmpDir")

        zip.extractAllTo(path.join(desktopPath, targetFolder), true)

        fs.rmSync(tmpDir, { recursive: true, force: true })
        fs.rmSync(uploadDir, { recursive: true, force: true })
      }
    }
  } catch (error) {
    console.log("AT-[ error &&&&&********** ]", error)
    res = {
      status: 401,
      msg: JSON.stringify(error),
    }
  } finally {
    ctx.body = res
    next()
  }
})

app.use(cors()).use(router.routes()).use(router.allowedMethods())

app.on("error", err => {
  console.error("server error", err)
})

export default (port = 7008) => {
  app.listen(port, () => {
    const webInterface = chalk.blue(`http://localhost:${port}`)

    console.log("uploadWebService running ", webInterface, "\n\n")
  })

  return app
}
